﻿using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace MT.WebApi.Core.Filters
{
    public class GlobaResultFilter : ActionFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ObjectResult objectResult)
            {
                if (objectResult.Value == null)
                {
                    //context.Result = new ObjectResult(new { Code = 404, Msg = "未找到资源" });
                    context.Result = new ObjectResult(string.Empty);
                }

                context.Result = objectResult.StatusCode == 200 ? 
                    new ObjectResult(objectResult.Value) :
                    new ObjectResult(objectResult.Value)
                        { StatusCode = objectResult.StatusCode, Value = objectResult.Value };
            }
            else if (context.Result is EmptyResult)
            {
                // context.Result = new ObjectResult(new { Code = 404, Msg = "未找到资源" });
                context.Result = new ObjectResult(string.Empty);
            }
            else if (context.Result is ContentResult result)
            {
                context.Result = new ObjectResult(new { Code = 200, Msg = string.Empty, result = result.Content });
            }
            else if (context.Result is StatusCodeResult)
            {
                // context.Result = new ObjectResult(new { code = (context.Result as StatusCodeResult).StatusCode, sub_msg = "", msg = "" });

                //var result = context.ModelState.Values.FirstOrDefault();
                //var dataRow = result.ToDataRow();
                //context.Result = new ObjectResult(new
                //{
                //    Code =
                //dataRow.ItemArray[2],
                //    Msg = result.Errors.FirstOrDefault().ErrorMessage
                //});

                //context.Result = new ObjectResult(new { Code = (context.Result as StatusCodeResult).StatusCode, Msg = string.Empty});

                context.Result = new ObjectResult(string.Empty);
            }
        }
    }
}
